import React, { PureComponent, Fragment } from 'react';
import styles from "../MForm.less"
import { connect } from 'dva';
import { InputItem, TextareaItem, Checkbox, Toast, Button } from 'antd-mobile';
import MToast from "../../Util/MToast"
import { isNull, getUUID, MI_S4 } from "../../../utils/helper"
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;
import moment from "moment";
interface Props {
	value: any,
	onChange?: Function,
	label?: any,
	required?: any,
	show_label?: any,
	tips?: any,
	label_width?: any,
	hasError: boolean,
	errorMsg: string,
	label_text_color?: string,
	label_text_align?: any,
	count?: any,
	mapping?: object,
	disabled?: any,
	readonly?: any,
	allow_clear?: any
}
interface State {
	[k: string]: any
}
export default class MyDataReceiveBox extends PureComponent<Props, State> {
	timer = null;
	textarea = null;
	public state: State = {
		value: this.props.value,
		isHex: false,//是否16进制
		isTime: false,//是否换行发送
	}
	componentWillReceiveProps(nextProps: Props) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			let value = nextProps.value;
			this.setState({
				value
			});
		}
	}
	receviceValue = (val) => {//处理接收到的数据 是否需要判断接收到的是什么类型的值
		let { isHex } = this.state;
		if (isHex) {
			val = this.strToHexCharCode(val);
		}
		this.changeValue(val);
	}
	changeValue = (value, isHex?, isAdd = true) => {
		let { isTime } = this.state;
		if (isNull(isHex)) {
			isHex = this.state.isHex;
		}
		let oldVal = this.state.value;
		if (isNull(oldVal)) {
			oldVal = "";
		}
		else {
			oldVal = oldVal + (isHex ? ' 0a ' : "\r\n")
		}
		if (isTime && isAdd) {
			let time = "["+moment().format("YYYY-MM-DD HH:mm:ss.SSS") + "] 收:  ";
			if(isHex){
				time = this.strToHexCharCode(time);
			}
			value = time + value;
		}
		if (isAdd === true) {//拼接
			value = oldVal + value;
		}
		else {
			value = value;
		}


		// 如果 是16进制 就限制只能输入16进制字符
		if (!('value' in this.props)) {
			this.setState({
				value: value
			});
		}
		this.triggerChange(value);
		setTimeout(() => {//滚动到底部
			var ele = this.textarea.textareaRef;
			ele.scrollTop = ele.scrollHeight;
		})
	};

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};

	componentDidMount() {
		// 告诉app 要把蓝牙接收到的数据传过来
	}
	onChange = (val?) => {
		let value = val;
		this.changeValue(value);
	};
	strToHexCharCode = (str) => {
		if (str === "") {
			return "";
		}
		var hexCharCode = [];
		// hexCharCode.push("0x");
		for (var i = 0; i < str.length; i++) {
			let hex = (str.charCodeAt(i)).toString(16);
			if (hex.length == 1) {
				hex = "0" + hex;
			}
			hexCharCode.push(hex);
		}
		return hexCharCode.join(" ");
	}
	hexCharCodeToStr = (hexStr) => {
		hexStr = hexStr.replace(/ /g, "");
		var rawStr =
			hexStr.substr(0, 2).toLowerCase() === "0x"
				?
				hexStr.substr(2)
				:
				hexStr;
		var len = rawStr.length;
		// if (len % 2 !== 0) {
		// 	alert("Illegal Format ASCII Code!");
		// 	return "";
		// }
		var curCharCode;
		var resultStr = [];
		for (var i = 0; i < len; i = i + 2) {
			let str = rawStr.substr(i, 2);
			if (str.length == 1 && str != " ") {
				str = "0" + str;
			}
			curCharCode = parseInt(str, 16); // ASCII Code Value
			resultStr.push(String.fromCharCode(curCharCode));
		}
		let result=resultStr.join("");
		result=result.replace(/ e6/g," 收");//
		return result;
	}

	render() {
		let { label, required, show_label, tips, label_width = 5, hasError, errorMsg, label_text_color, label_text_align = "left" } = this.props;

		let isShowLabel = isNull(show_label) || show_label == 1;
		let isRequired = required == 1;
		let { value, isHex } = this.state;
		let requiredClass = "am-list-item am-input-item am-list-item-middle mi-text mi-datasendbox";
		if (isRequired) {
			requiredClass += " required"
		}
		if (hasError) {
			requiredClass += " am-input-error"
		}
		if (!isNull(label_text_align)) {
			requiredClass += " label-text-align-" + label_text_align
		}
		let labelClass = "am-input-label am-input-label-";
		if (isNull(label_width)) {
			labelClass += "3"
		}
		else {
			labelClass += label_width
		}
		return (
			<div className={requiredClass} style={{ fontSize: "16px" }} data-flex="box:first">
				{
					isShowLabel ? <div className={labelClass} style={{ color: label_text_color }}>
						{label}
					</div> : <div></div>
				}
				<div style={{ color: "#888", paddingRight: "0" }} className="am-list-line" data-flex="dir:left box:last">
					<div>
						<div data-flex="dir:left">
							<AgreeItem onChange={(e) => {
								let checked = e.target.checked;
								this.setState({
									isHex: checked
								})
								if (!isNull(value)) {
									if (checked) {
										this.changeValue(this.strToHexCharCode(value), checked, false);
									}
									else {
										this.changeValue(this.hexCharCodeToStr(value), checked, false);
									}
								}

							}}>十六进制显示</AgreeItem>
							<AgreeItem onChange={(e) => {
								let checked = e.target.checked;
								this.setState({
									isTime: checked
								})
							}}>时间戳</AgreeItem>
						</div>
						<TextareaItem
							ref={e => this.textarea = e}
							editable={false}
							onBlur={() => {
								this.timer = setTimeout(() => {
									window.scrollTo(0, 0)
								}, 10);
							}} style={{ height: "150px" }} value={value} onChange={this.changeValue}></TextareaItem>
						<div style={{ margin: "10px 0" }} data-flex>
							<Button size="small" onClick={() => {
								if (!('value' in this.props)) {
									this.setState({
										value: ""
									});
								}
								this.triggerChange("");
							}}>清除接收</Button>
							<Button size="small" style={{ marginLeft: "10px" }} onClick={() => {
								this.receviceValue(MI_S4());
							}}>模拟接收</Button>
						</div>
					</div>
					<div className="am-input-error-extra mi" onClick={(e) => {
						e.stopPropagation();
						MToast.info(errorMsg, 2, null, false)
					}} style={{ minWidth: "15px", width: "15px" }}
					/>
				</div>
			</div>
		)
	}
	componentWillUnmount() {
		clearTimeout(this.timer);
	}
}
